<template>
    <div class="main_box" style="padding:10px">
      <div class="add_wrap">
        <div class="tit">
          <h2>基础信息</h2>
          <el-button type="success" plain size="small" icon="fa fa-mail-forward" @click="returnList">返回</el-button>
        </div>
        <el-form :model="dataForm" ref="dataForm" label-width="200px" :rules="roleRules" :validate-on-rule-change="false">
          <el-row>
            <el-form-item label="SSO用户：" prop="casUserId">
              <el-select v-model="dataForm.casUserId" filterable placeholder="请选择SSO用户" :loading="loading"
                loading-text="正在加载中..." @visible-change="listData">
                <el-option v-for="item in options" :key="item.id" :label="item.userName" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="用户类型：" prop="userRole">
              <el-select v-model="dataForm.userRole" placeholder="请选择用户类型">
                <el-option label="管理员" :value="1"></el-option>
                <el-option label="社区管理员" :value="5"></el-option>
                <el-option label="业务员" :value="10"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="详细地址：" prop="liveAddress">
              <el-input v-model="dataForm.liveAddress" :clearable="true"></el-input>
            </el-form-item>
            <el-form-item label="公司：" prop="departId">
              <el-cascader v-model="dataForm.departId" :options="departList"
                :props="{ value: 'departId', label: 'departName', children: 'childrens', checkStrictly: true, emitPath: false }"
                filterable>

              </el-cascader>
            </el-form-item>
            <el-form-item label="平台商户：" prop="businessId" v-show="dataForm.userRole==10">
              <el-select v-model="dataForm.businessId" placeholder="请选择平台商户" clearable filterable>
                <el-option v-for="item in businessList" :label="item.name" :value="item.id" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否语音提醒" prop="isRemind">
              <el-radio-group v-model="dataForm.isRemind">
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="备注：" prop="remark">
              <el-input v-model="dataForm.remark" :clearable="true"></el-input>
            </el-form-item>
          </el-row>
          <div class="tit" v-show="dataForm.userRole > 1">
            <h2>管理区域</h2>
            <el-button icon="el-icon-plus" type="success" plain size="medium" circle @click="addBtn">
            </el-button>
          </div>
          <el-row v-if="dataForm.userRole > 1">
            <el-table :data="dataForm.adminVillage" style="width:max-content;margin-top: 20px;">
              <el-table-column label="操作" width="100" align="center">
                <template slot-scope="scope">
                  <el-button icon="el-icon-minus" type="danger" plain size="medium" circle @click="subBtn(scope.$index)">
                  </el-button>
                </template>
              </el-table-column>

              <el-table-column label="地区" width="320" align="center">
                <template slot-scope="scope">
                  <Region style="width:300px" ref="region" :streetValues="scope.row.streetIds"
                    @regionChange="handleItemChange" :isChangeOnSelect="true" :index="scope.$index"></Region>
                </template>
              </el-table-column>
              <el-table-column label="小区" width="240px" align="center">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.villageIds" @focus="handleVillageFocus(scope.row.streetIds, scope.$index)"
                    multiple filterable clearable>
                    <el-option v-for="item in scope.row.villageList" :value="item.id" :label="item.name" :key="item.id">

                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
          <el-row>
            <el-form-item>
              <el-button plain type="primary" @click="sureAddClick">保 存</el-button>
              <el-button @click="returnList">取 消</el-button>
            </el-form-item>
          </el-row>
        </el-form>
      </div>
    </div>
  </template>

  <script>
  import AuthApi from "@/api/system/auth";
  import * as message from "@/constants/message";
  import Region from "@/components/Region";
  import VillageApi from "@/api/address/village"
  import DepartApi from "../../api/system/depart";
  import BusinessApi from "@/api/business/business";
  import { listBindSsoUser } from "@/api/system/ssoUser";
  export default {
    data() {
      return {
        dataForm: {
          casUserId: "",
          remark: "",
          isRemind: 1,
          userRole: "",
          liveAddress: "",
          departId: "",
          businessId:"",
          adminVillage: [
            {
              provinceId: "",
              cityId: "",
              areaId: "",
              streetId: '',
              villageId: "",
              villageIds: [], // 新增时用到
              levels: "",
              streetIds: [],//数组id到时候需要全部删掉
              villageList: [],//小区列表,确认添加和删除数据的时候需要删除
            }
          ],
        },
        adminVillage: [],
        departList: [],
        businessList:[],
        roleRules: {
          isRemind: [
            { required: true, message: "请选择是否语音提醒", trigger: "change" }
          ],
        },
        options: [],
        loading: false
      };
    },
    components: {
      Region
    },
    beforeRouteLeave(to, from, next) {
      to.meta.keepAlive = true;
      next();
    },
    mounted() {
      this.listData();
      this.init();
    },
    methods: {
      init() {
        this.getDepartList()
        this.getBusinessList()
      },
      listData() {
        this.options = [];
        this.loading = true;
        listBindSsoUser().then(data => {
          this.options = data.data
          this.loading = false;
        });
      },
      // 禁止输入空格
      keydown(e) {
        if (e.keyCode == 32) {
          e.returnValue = false;
        }
      },
      getDepartList() {
        DepartApi.listDeparts().then(res => {
          this.departList = res.data || []
        })
      },
      // 获取商户列表
      getBusinessList() {
            BusinessApi.listIdNameVo().then(res => {
                this.businessList = res.data
            })
        },
      // 获取cascader所需的departId数组
      // getDepartIds(){
      //     const departId = []
      //     this.dataForm.departId.forEach(item=>{
      //       const val = this.$Utils.filterTreeToArr(this.departList,{departId:item},'departId').map(item=>item.departId)
      //       departId.push(val)
      //     })
      //     this.dataForm.departId = departId
      //   },
      // 获取小区列表
      listVillage(streetIds, index) {
        let param = {
          provinceId: streetIds[0],
          cityId: streetIds[1],
          areaId: streetIds[2],
          streetId: streetIds[3],
          name: "",
        }
        VillageApi.villageList(param).then(res => {
          this.$set(this.dataForm.adminVillage[index], "villageList", res.data)
        })
      },

      handleItemChange(val) {
        let region = this.dataForm.adminVillage[val.index]
        region.villageList = [] //清空小区列表
        region.villageId = "" //清空对应的小区id
        region.levels = "" //每次修改都重新修改赋值层级
        region.provinceId = val.provinceId;
        region.provinceName = val.provinceName;
        region.cityId = val.cityId;
        region.cityName = val.cityName;
        region.areaId = val.areaId;
        region.areaName = val.areaName;
        region.streetId = val.streetId
        region.streetName = val.streetName
        region.levels = val.levels

        if (val.provinceId) {
          region.streetIds = [val.provinceId, val.cityId, val.areaId, val.streetId];
        } else {
          region.streetIds = []
        }

        if (val.levels == 1 || val.levels == 2) {
          // 只选到第一级和第二级别那么就直接清空
          region.villageList = [] //清空小区列表
          region.villageId = "" //清空对应的小区id
          this.$refs.region.clearStreetIds()
          this.$message.error("请至少选至三级地区")
        }
        // region.levels = "" //每次修改都重新修改赋值层级
        // region.streetIds.forEach((item,index)=>{
        //   if(item){
        //     region.levels = index+1
        //   }
        // })
      },

      addBtn() {
        this.dataForm.adminVillage.push({
          provinceId: "",
          cityId: "",
          areaId: "",
          streetId: '',
          villageId: "",
          villageIds: [],
          levels: "",
          streetIds: [],
          villageList: [],
        })
      },
      subBtn(index) {
        this.dataForm.adminVillage.splice(index, 1)
      },
      handleVillageFocus(streetIds, index) {
        // 点击小区的时候调用接口
        let levels = this.dataForm.adminVillage[index].levels
        if (levels == 3 || levels == 4) {
          let param = {
            provinceId: streetIds[0],
            cityId: streetIds[1],
            areaId: streetIds[2],
            streetId: streetIds[3],
            name: "",
          }
          VillageApi.villageList(param).then(res => {
            this.$set(this.dataForm.adminVillage[index], "villageList", res.data)  //数组里面的数据修改是不能实现响应式的
          })
        }
      },

      sureAddClick() {
        this.$refs.dataForm.validate(valid => {
          //
          if (valid) {
            if (this.dataForm.userRole > 1) {
              // 把列表里面没有数据的全部清空掉
              let arr = []
              this.dataForm.adminVillage.forEach(item => {
                if (item.provinceId) {
                  arr.push(item)
                }
              })
              if (arr.length == 0) {
                this.$message.error("请至少选择一个管理区域")
                return
              }
              //this.dataForm.adminVillage = arr
              let arrPs = []
              let arrVs = []
              arr.forEach(item => {
                if (item.villageIds && item.villageIds.length > 0) {
                  arrVs = item.villageIds.map(item2 => {
                    return {
                      provinceId: item.provinceId,
                      cityId: item.cityId,
                      areaId: item.areaId,
                      streetId: item.streetId,
                      villageId: item2,
                      levels: 5
                    }
                  })
                } else {
                  arrPs.push({
                    provinceId: item.provinceId,
                    cityId: item.cityId,
                    areaId: item.areaId,
                    streetId: item.streetId,
                    levels: item.levels
                  });
                }
              })
              // 拼接集合
              this.adminVillage = arrPs.concat(arrVs)
              // 把this.dataForm.adminVillage里面的数据筛选出需要的字段
              /*this.adminVillage = arr.map(item=>{
                  return {
                    provinceId: item.provinceId,
                    cityId: item.cityId,
                    areaId: item.areaId,
                    streetId: item.streetId,
                    villageId: item.villageId,
                    levels: item.villageIds?5:item.levels
                  }
              })*/
            }

            this.$confirm(
              message.MSG_CONFIRM_SAVE,
              message.TITLE_PROMPT,
              {}
            ).then(() => {
              this.addData();
            });
          }
        });
      },
      addData() {
        let data = {
          remark: this.dataForm.remark,
          isRemind: this.dataForm.isRemind,
          userRole: this.dataForm.userRole,
          liveAddress: this.dataForm.liveAddress,
          adminVillage: this.adminVillage,
          departId: this.dataForm.departId,
          casUserId: this.dataForm.casUserId
        };
        if(data.userRole==10){
          data.businessId = this.dataForm.businessId
        }
        AuthApi.addAdmin(data).then(data => {
          this.$Utils.notifySuccess();
          this.returnList();
        });
      },
      returnList() {
        this.$store.dispatch("delView", this.$route);
        this.$router.back();
      }

    }
  };
  </script>
  <style lang="scss" scoped>
@import "@/assets/css/views/add.scss";
</style>
